package hqb.dev.webdeploy.flow;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * 文件替换步骤
 *
 * @author HQB--2024-04-22
 **/
@Slf4j
public class FlowStepReplace extends FlowStep {

    private final List<FlowStepReplaceRun> runs;

    public FlowStepReplace(String name, String desc, JSONObject y, File unzipDir) {
        super(name, desc);
        JSONArray list = y.getJSONArray("list");
        this.runs = list.stream()
                .map(x -> new FlowStepReplaceRun((JSONObject) x, unzipDir))
                .toList();
    }

    @Override
    public void execute() {
        for (FlowStepReplaceRun r : runs) {
            File from = r.getSrc();
            File to = r.getDest();
            File rename = null;
            if (to.exists()) rename = FileUtil.rename(to, to.getName() + ".bak" + IdUtil.fastSimpleUUID(), true);
            if (from.exists()) {
                if (from.isDirectory()) {
                    to = to.getParentFile();
                }
                FileUtil.copy(from, to, true);
            }
            if (rename != null && rename.exists()) FileUtil.del(rename);
        }
    }
}
